package com.zixun.controller;

import com.zixun.config.WebApiConfig;
import com.zixun.model.ApplyInfo;
import com.zixun.model.Offer;
import com.zixun.model.User;
import com.zixun.model.request.Request;
import com.zixun.model.request.RequestComment;
import com.zixun.model.request.RequestImage;
import com.zixun.repository.ApplyInfoRepository;
import com.zixun.repository.OfferRepository;
import com.zixun.repository.request.RequestCommentRepository;
import com.zixun.repository.request.RequestImageRespository;
import com.zixun.repository.request.RequestRepository;
import com.zixun.service.RequestService;
import com.zixun.service.UserService;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Created by Basil on 16/8/23.
 */
@RestController
@Transactional
@RequestMapping("api/request/")
public class RequestWebApi {
    @Autowired
    RequestRepository requestRepository;

    @Autowired
    RequestCommentRepository requestCommentRepository;

    @Autowired
    RequestImageRespository requestImageRespository;

    @Autowired
    ApplyInfoRepository applyInfoRepository;

    @Autowired
    OfferRepository offerRepository;

    @Autowired
    RequestService requestService;

    @Autowired
    UserService userService;

    /**
     * @api {GET} /api/request/getMyRequestList 获取我的问题列表
     * @apiName getMyRequestList
     * @apiGroup request
     * @apiVersion 0.0.1
     * @apiDescription 获取我的问题列表
     * @apiParam {String} userId 用户编号
     * @apiParam {Integer} countPerPage 分页显示数量
     * @apiParam {Integer} pageIndex	当前页码
     * @apiParam {Integer} type 问题类型 0:我的提问 1:我的回答
     * @apiSuccessExample 返回值: HTTP/1.1 200 OK
     * {
     * "returnValue":【1:成功, 2:参数错误,3:服务器异常,10:用户不存在, 整型】,
     * "errMsg":【错误信息, 字符串】.
     * "data":[{
     * "title":【问题标题,字符串】
     * "type":【状态 0:普通 1:紧急, 整型】
     * }],
     * }
     */
    @RequestMapping("getMyRequestList")
    public Map<String,Object> getMyRqeustList (String userId,Integer pageIndex,Integer countPerPage,Integer type){
        Map<String,Object> result = new HashMap<>();
        if(userId==null||pageIndex==null||countPerPage==null||(type!=0&&type!=1)||type==null){
            result.put("errMsg","参数错误");
            result.put("returnValue",2);
            return result;
        }
        if(!userService.isUserExist(Integer.valueOf(userId))){
            result.put("errMsg","用户不存在");
            result.put("returnValue",10);
            return result;
        }
        try {
            List list = new ArrayList();
            //我的提问
            if(type==0){
                Page<Request> page = requestService.findAllByUserIdRequest(Integer.valueOf(userId),pageIndex,countPerPage);
                for(Request request:page){
                    Map<String,Object> map = new HashMap<>();
                    map.put("title", request.getTitle());
                    if(request.getType()==null){
                        request.setType(0);
                        requestRepository.save(request);
                    }
                    map.put("type",request.getType());
                    list.add(map);
                }
            }
            //我的回答
            if(type==1){
                Page<RequestComment> page= requestService.findAllByReplyUserIdRequest(Integer.valueOf(userId),pageIndex,countPerPage);
                for(RequestComment requestComment:page){
                    Map<String,Object> map = new HashMap<>();
                    Request request = requestRepository.findById(requestComment.getRequestId());
                    map.put("title",request.getTitle());
                    if(request.getType()==null){
                        request.setType(0);
                        requestRepository.save(request);
                    }
                    map.put("type",request.getType());
                    list.add(map);
                }
            }
            result.put("data",list);
            result.put("errMsg","成功");
            result.put("returnValue",1);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("errMsg","服务器异常");
            result.put("returnValue",3);
            return result;
        }
    }

    /**
     * @api {POST} /api/request/criticalRequest 紧急提问
     * @apiName criticalRequest
     * @apiGroup request
     * @apiVersion 0.0.1
     * @apiDescription 紧急提问
     * @apiParamExample 请求参数{JSON}
     * {
     * "userId":【用户编号, 字符串】,
     * "title":【标题，字符串】,
     * "price":【价格，整形】,
     * "content":【内容，字符串】,
     * "address":【地址，字符串】,
     * "images":["image1","image2"]
     * }
     * @apiSuccessExample 返回值: HTTP/1.1 200 OK
     * {
     * "returnValue":【1:成功,2:参数错误,3:服务器异常,10:用户不存在,11:JSON参数异常 整型】,
     * "errMsg":【错误信息 , 字符串】,
     * }
     */
    @RequestMapping("criticalRequest")
    public Map<String,Object> criticalRequest(@RequestBody String data){
        Map<String,Object> result = new HashMap();
        JSONObject jo = new JSONObject(data);
        try {
            if(jo.isNull("userId")||jo.isNull("title")||jo.isNull("price")||jo.isNull("content")){
                result.put("errMsg","参数异常");
                result.put("returnValue",2);
                return result;
            }
            String address = null;
            if (!jo.isNull("address")) {
                address = jo.getString("address");
            }
            Request request = new Request();
            if(!userService.isUserExist(Integer.valueOf(jo.getString("userId")))){
                result.put("errMsg","用户不存在");
                result.put("returnValue",10);
                return result;
            }
            request.setUserId(Integer.valueOf(jo.getString("userId")));
            request.setTitle(jo.getString("title"));
            request.setPrice(jo.getInt("price"));
            request.setAddress(address);
            request.setContent(jo.getString("content"));
            request.setCreateTime(new Date());
            request.setType(1);
            request.setUpdateTime(new Date());
            request.setNumber(0);
            request.setStatus(0);
            requestRepository.save(request);
            if(!jo.isNull("images")){
                JSONArray imageJsonArray = jo.getJSONArray("images");
                for(int i=0 ;i<imageJsonArray.length();i++){
                    String imageName = imageJsonArray.getString(i);
                    RequestImage requestImage = new RequestImage();
                    requestImage.setRequestId(request.getId());
                    requestImage.setName(imageName);
                    requestImageRespository.save(requestImage);
                }
            }
            result.put("errMsg","成功");
            result.put("returnValue",1);
            return result;
        } catch (JSONException e) {
            e.printStackTrace();
            result.put("errMsg","JSON参数异常");
            result.put("returnValue",11);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("errMsg","服务器异常");
            result.put("returnValue",3);
            return result;
        }
    }
    /**
     * @api {GET} /api/request/getRequestList 获取问题列表
     * @apiName getRequestList
     * @apiGroup request
     * @apiVersion 0.0.1
     * @apiDescription 获取问题列表
     * @apiParam {String} userId 用户编号
     * @apiParam {Integer} countPerPage 分页显示数量
     * @apiParam {Integer} pageIndex	当前页码
     * @apiParam {Integer} type 问题类型 0:一般回答 1:紧急回答
     * @apiSuccessExample 返回值: HTTP/1.1 200 OK
     * {
     * "returnValue":【1:成功, 2:参数错误,3:服务器异常,10:用户不存在, 整型】,
     * "errMsg":【错误信息, 字符串】.
     * "data":[{
     * "userName":【用户名称,字符串】
     * "city":【城市,字符串】,
     * "createTime":【创建时间,长整型】,
     * "title":【标题,字符串】,
     * "content":【内容,字符串】,
     * "status":【0:未解决 1:已解决,整型】,
     * "price":【价格,整型】,
     * "number":【出价人数, 整型】,
     * }],
     * }
     */
    @RequestMapping("getRequestList")
    public Map<String,Object> getRequestList(String userId ,Integer pageIndex,Integer countPerPage,Integer type){
        Map<String,Object> result = new HashMap<>();
        if(userId==null||pageIndex==null||countPerPage==null||type==null||(type!=1&&type!=0)){
            result.put("errMsg","参数错误");
            result.put("returnValue",2);
            return result;
        }
       if(!userService.isUserExist(Integer.valueOf(userId))){
           result.put("errMsg","用户不存在");
           result.put("returnValue",10);
           return result;
        }
        try {
            Page<Request> page=requestService.findAllByUserIdAndTypeRequest(Integer.valueOf(userId),pageIndex,countPerPage,type);
            List list =new ArrayList<>();
            for(Request request:page){
                Map<String,Object> map =new HashMap<>();
                User user=userService.getUserByUserId(Integer.valueOf(userId));
                map.put("userName",user.getName());
                map.put("city",user.getCity());
                map.put("createTime",request.getCreateTime().getTime());
                map.put("title",request.getTitle());
                map.put("content",request.getContent());
                if(request.getStatus()==null){
                    map.put("status",0);
                }else {
                    map.put("status", request.getStatus());
                }
                if(request.getPrice()==null){
                    request.setPrice(0);
                    requestRepository.save(request);
                }
                map.put("price",request.getPrice());
                if(request.getNumber()==null){
                    request.setNumber(0);
                    requestRepository.save(request);
                }
                map.put("number", request.getNumber());
                list.add(map);
            }
            result.put("errMsg","成功");
            result.put("returnValue",1);
            result.put("data",list);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("errMsg","服务器异常");
            result.put("returnValue",3);
            return result;
        }
    }

    /**
     * @api {GET} /api/request/getCriticalRequestInfo 获取我的紧急问答详情
     * @apiName getCriticalRequestInfo
     * @apiGroup request
     * @apiVersion 0.0.1
     * @apiDescription 获取我的紧急问答详情
     * @apiParam {Integer} id 问答编号
     * @apiSuccessExample 返回值: HTTP/1.1 200 OK
     * {
     * "returnValue":【1:成功, 2:参数错误,3:服务器异常,11:问题不存在,10:用户不存在, 整型】,
     * "errMsg":【错误信息, 字符串】.
     * "data":{
     * "createTime":【创建时间,长整型】,
     * "title":【标题,字符串】,
     * "content":【内容,字符串】,
     * "address":【地址,字符串】,
     * "images":["image1","image2"],
     * "offer":[
     *  "isAccept":【是否被采纳,整型】,
     *  "price":【价格,整型】,
     *  "name":【名称,字符串】
     * ]
     * }
     * }
     */
    @RequestMapping("getCriticalRequestInfo")
    public Map<String,Object> getCriticalRequestInfo(Integer id){
        Map<String,Object> result = new HashMap();
        try {
            if(id==null){
                result.put("errMsg","参数错误");
                result.put("returnValue",2);
                return result;
            }
            Request request=requestService.findByIdAndType(id,1);
            if(request==null){
                result.put("errMsg","问题不存在");
                result.put("returnValue",11);
                return result;
            }
            Map<String,Object> map = new HashMap<>();
            map.put("title",request.getTitle());
            map.put("content",request.getContent());
            map.put("createTime",request.getCreateTime().getTime());
            map.put("address",request.getAddress());
            //获取图片
            List images = new ArrayList();
            List<RequestImage> requestImages = requestService.findByRequestId(id);
            for(RequestImage requestImage : requestImages){
                Map imageMap = new HashMap<>();
                imageMap.put("image", WebApiConfig.IMAGE_URL+requestImage.getName());
                images.add(imageMap);
            }
            map.put("images",images);
            //获取出价信息
            List offers = new ArrayList<>();
            List<Offer> offerList = offerRepository.findByProduceIdAndType(id,1);
            for(Offer offer:offerList){
                Map offerMap = new HashMap<>();
                if(offer.getIsAccept()==null){
                    offer.setIsAccept(0);
                    offerRepository.save(offer);
                }
                offerMap.put("isAccept",offer.getIsAccept());
                if(offer.getPrice()==null){
                    offer.setPrice(0);
                    offerRepository.save(offer);
                }
                offerMap.put("price",offer.getPrice());
                ApplyInfo applyInfo=applyInfoRepository.findByUserId(offer.getUserId());
                offerMap.put("name",applyInfo.getRealName());
                offers.add(offerMap);
            }
            map.put("offers",offers);
            result.put("data",map);
            result.put("errMsg",1);
            result.put("returnValue","成功");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("errMsg","服务器异常");
            result.put("returnValue",3);
            return result;
        }
    }

    /**
     * @api {GET} /api/request/getRequestInfo 获取我的普通问答详情
     * @apiName getRequestInfo
     * @apiGroup request
     * @apiVersion 0.0.1
     * @apiDescription 获取我的普通问答详情
     * @apiParam {Integer} id 问答编号
     * @apiSuccessExample 返回值: HTTP/1.1 200 OK
     * {
     * "returnValue":【1:成功, 2:参数错误,3:服务器异常,11:问题不存在,10:用户不存在, 整型】,
     * "errMsg":【错误信息, 字符串】.
     * "data":{
     * "createTime":【创建时间,长整型】,
     * "title":【标题,字符串】,
     * "content":【内容,字符串】,
     * "address":【地址,字符串】,
     * "images":["image1","image2"],
     * "comments":[
     *  "replyUserName":【回复人姓名,整型】,
     *  "commentCreateTime":【回复时间,长整型】,
     *  "comment":【回复内容,字符串】
     *  "replyUserImage":【回复人头像,字符串】
     * ]
     * }
     * }
     */
    @RequestMapping("getRequestInfo")
    public Map<String,Object> getRequestInfo(Integer id){
        Map<String,Object> result =new HashMap<>();
        try {
            if(id==null){
                result.put("errMsg","参数错误");
                result.put("returnValue",2);
                return result;
            }
            Request request=requestService.findByIdAndType(id,0);
            if(request==null){
                result.put("errMsg","问题不存在");
                result.put("returnValue",11);
                return result;
            }
            Map<String,Object> map = new HashMap<>();
            map.put("title",request.getTitle());
            map.put("content",request.getContent());
            map.put("createTime",request.getCreateTime().getTime());
            map.put("address",request.getAddress());
            //获取图片
            List images = new ArrayList();
            List<RequestImage> requestImages = requestService.findByRequestId(id);
            for(RequestImage requestImage : requestImages){
                Map imageMap = new HashMap<>();
                imageMap.put("image", WebApiConfig.IMAGE_URL+requestImage.getName());
                images.add(imageMap);
            }
            map.put("images",images);
            //获取评论
            List comments = new ArrayList<>();
            List<RequestComment> requestComments = requestService.findByRequestIdCom(id);
            map.put("count",requestComments.size());
            for(RequestComment requestComment:requestComments){
                Map commentMap = new HashMap<>();
                commentMap.put("comment",requestComment.getComment());
                commentMap.put("commentCreateTime",requestComment.getCreateTime().getTime());
                ApplyInfo applyInfo = applyInfoRepository.findByUserId(requestComment.getReplyUserId());
                commentMap.put("replyUserName",applyInfo.getRealName());
                User user = userService.getUserByUserId(requestComment.getReplyUserId());
                commentMap.put("replyUserImage",WebApiConfig.IMAGE_URL+user.getHeadPicture());
                comments.add(commentMap);
            }
            map.put("comments",comments);
            result.put("data",map);
            result.put("errMsg","成功");
            result.put("returnValue",1);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("errMsg","服务器异常");
            result.put("returnValue",3);
            return result;
        }
    }
}
